package org.lyj.samples;

import io.vertx.core.buffer.Buffer;
import io.vertx.core.eventbus.MessageCodec;

import java.io.*;
import java.util.Map;

public class CustomizeMessageCodec implements MessageCodec<Map<String, Object>, Map<String, Object>> {

    @Override
    public void encodeToWire(Buffer buffer, Map<String, Object> hashMap) {
        final ByteArrayOutputStream b = new ByteArrayOutputStream();
        ObjectOutputStream o = null;
        try {
            o = new ObjectOutputStream(b);
            o.writeObject(hashMap);
            o.close();
            buffer.appendBytes(b.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (o != null) {
                try {
                    o.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public Map<String, Object> decodeFromWire(int pos, Buffer buffer) {
        final ByteArrayInputStream b = new ByteArrayInputStream(buffer.getBytes());
        Map<String, Object> msg = null;
        try (ObjectInputStream o = new ObjectInputStream(b)){
            msg = (Map<String, Object>) o.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return msg;
    }

    @Override
    public Map<String, Object> transform(Map<String, Object> hashMap) {
        return hashMap;
    }

    @Override
    public String name() {
        return "mapCodec";
    }

    @Override
    public byte systemCodecID() {
        return -1;
    }

    public static MessageCodec<Map<String, Object>, Map<String, Object>> create() {
        return new CustomizeMessageCodec();
    }
}
